$(function(){
    paginationInit();
});
//此处代码重复
var paginationMaxLength=8;//分页栏的最大显示条数
var onlyOnePageIsShow = true;//只有一页的时候是否显示
function paginationInit(){
    $('[am-pagination =pagination_new ]').each(function(){
        initPagination($(this));
    });
}

function initPagination(element){

    element.html('');
    var pagenumber = element.attr('pagenumber');
    var totalpage = element.attr('totalpage');
    var pMaxLength = element.attr('paginationMaxLength');
    var onePageIsShow = element.attr('onlyOnePageIsShow');
    // console.log(totalpage)
    if(isNeedPagination(Number(totalpage),onePageIsShow)){
        var content = '<ul class="am-pagination am-pagination-centered"><li value="0"><a href="javascript:void(0);">«</a></li>';
        for(var i =1; i<=totalpage;i++){
            content +='<li value="'+i+'"><a href="javascript:void(0);">'+i+'</a></li>'
        }
        content +='<li value="-1"><a href="javascript:void(0);">»</a></li></ul>';
        element.append(content);
        element.children('ul').children('li[value='+pagenumber+']').attr('class','am-active');
        setDisplayMaxLength(element,pMaxLength);
        addClickListener(element);
    }
}

function setDisplayMaxLength(element,len){
    var currentpage =  Number(element.attr('pagenumber'));
    var totoalpage = Number(element.attr('totalpage'));
    if(checkParamIsPositiveInteger(len)){
        len = Number(len);
    }else{
        len =paginationMaxLength;
    }
    if(len<totoalpage){
        var temp1 = parseInt((len-1)/2);
        var temp2 = parseInt(len/2);
        if(temp1<temp2){
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1 + 1;
        }else{
            var leftstart = currentpage - temp1;
            var rightend = currentpage + temp1;
        }
        if(leftstart<1){
            rightend +=(1-leftstart);
            leftstart = 1;
        }
        if(rightend>totoalpage){
            if(leftstart>1){
                leftstart -=(rightend-totoalpage);
            }
            rightend =totoalpage;
        }
        if(leftstart<1){
            leftstart=1
        }
        while(leftstart >1){
            element.children('ul').children('li[value = '+(--leftstart)+']').css('display','none');
        }
        while(rightend <totoalpage){
            element.children('ul').children('li[value = '+(++rightend)+']').css('display','none');
        }
    }
}

function isNeedPagination(totalpage,settingfromHTML){
    var condition ;
    if(settingfromHTML == "true"){
        condition = true;
    }else if(settingfromHTML == 'false'){
        condition = false;
    }else {
        condition = onlyOnePageIsShow;
    }
    if(condition && totalpage<1){
        return false;
    }else if(!condition && totalpage<=1){
        return false;
    }
    return true;
}
//根据页面pagenumber、my_totoalpage更新分页，参数element传的是分页的容器

function addClickListener(element){
    element.children('ul').children('li').bind('click',function(){
        var temp = Number($(this).attr('value'));
        var pagenumber = Number($(this).parent().parent().attr('pagenumber'));
        var totalpage = Number($(this).parent().parent().attr('totalpage'));
        if(temp == 0){
            temp = pagenumber-1;
        }else if(temp == -1){
            temp = pagenumber+1;
        }
        if(temp != pagenumber && temp !=0 && temp<=totalpage){
            $(this).parent().parent().attr('pagenumber',temp);
            paginationClick(element.attr("id"));
            initPagination(element);
        }
        return false;
    })
}
function checkParamIsPositiveInteger(param){
    var reg = /^[1-9]+[0-9]*]*$/;
    return reg.test(param);
}

//用户需要自己实现的点击事件，参数为分页容器的id
function paginationClick(pagination_id){
    var pagenumber = $('#'+pagination_id+'').attr('pagenumber');
    var totalpage = $('#'+pagination_id+'').attr('totalpage');
    JSON.stringify(pagenumber);
    $.ajax({
        type:"POST",
        url:constUrl+"HostGroupList",
        dataType:"json",
        data: {
            method : "getPagedGroup",
            onePageCount: "10",
            currentPage: pagenumber
        },
        success:function(data){
        		if(data.result=="false")//校验返回数据
        			return;
            addBox(data.message.pagedGrouplist);
        },
        error:function (e) {
            console.log(e);
        }
    });
}

function addBox(data){
    $("tr").remove(".addTr");

    for(var i=0;i<data.length;i++) {
        $("#nodeClassificationTableList").children("tbody").append(
            "<tr class='addTr'>" +
            "<td>"+(i+1)+"</td>" +
            "<td>"+data[i].GROUP_NAME+"</td>" +
            "<td>"+data[i].HOSTS+"</td>" +
            "<td>" +
            "<div type='button' class='am-btn am-btn-default am-radius' onclick=\"updateC('"+data[i].GROUP_NAME+"');\">修改</div>" +
            "<div type='button' class='am-btn am-btn-default am-radius'onclick=\"deleteGroup('"+data[i].GROUP_NAME+"');\">删除</div>" +
            "</td>" +
            "</tr>"
        );
    }
}

function addC() {
    layer.ready(function() {
        //官网欢迎页
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '添加计算节点组别',
            fix: false,
            scrollbar:false,
            shadeClose: true,
            maxmin: true,
            area: ['450px', '300px'],
            content: constUrl+'views/node/group/register.action'
        });
    });
}
function updateC(data) {
    layer.ready(function() {
        //官网欢迎页
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '添加计算节点组别',
            fix: false,
            scrollbar:false,
            shadeClose: true,
            maxmin: true,
            area: ['450px', '300px'],
            content: constUrl+'views/node/group/update.action?g='+data,
            success:function(data,index){
            		//alert(data)
            		//$("#name").val(data);
            	}
        });
    });
}
// 删除列表内容
function deleteGroup(groupName){
	var index = parent.layer.getFrameIndex(window.name);
	layer.confirm('确定要删除分组"'+groupName+'"吗？', {
        btn: ['确定','取消'] //按钮
    },function(){
    	$.ajax({
		    method : 'delete',
		    url : 'conf/hosts/group/'+groupName+'.action',
		    dateType:'json',
		    //data : $('#addHostGroup').serializeArray(),
		    success : function(data) {
		    	if(data.resultCode=='000000'){
		    		layer.confirm('操作成功！',{
		                btn:['确定']
		            },function () {
		                parent.location.reload(index);
		            });
		    	}else
		    		layer.msg('操作失败')
		       //alert(data);
		     }
	    });
	 },function(){
		 layer.msg('操作取消', {
	            time: 1000 //1s后自动关闭
	      });
	 });
		return false;
}